package cn.wzg.netbase;

import static java.net.HttpURLConnection.HTTP_OK;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import cn.wzg.netbase.http.HttpCallbackStringListener;
import cn.wzg.netbase.http.HttpUrlConnectionUtils;
import cn.wzg.netbase.utils.StreamUtil;

public class LoginActivity extends AppCompatActivity {
    private EditText et_name, et_pwd;
    private String sessions;
    private String link = "https://www.wanandroid.com/user/login";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            String json= (String) msg.obj;
            System.out.println(json);
            try {
                JSONObject object=new JSONObject(json);
                int errorCode = object.optInt("errorCode");
                if(errorCode==0){
                    //Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent(LoginActivity.this,CollectActivity.class);
                    intent.putExtra("session",sessions);
                    startActivity(intent);
                }else{
                    String string = object.optString("errorMsg");
                    Toast.makeText(LoginActivity.this, string, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        et_name = findViewById(R.id.et_name);
        et_pwd = findViewById(R.id.et_pwd);
    }

    public void login(View view) {
        String name = et_name.getText().toString();
        String pwd = et_pwd.getText().toString();
//        String param = "username=" + URLEncoder.encode(name) +
//                "&password=" + URLEncoder.encode(pwd);
//        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    URL url = new URL(link);//创建URL对象
//                    //获取HttpsURLConnection对象
//                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//                    conn.setRequestMethod("POST");//设置请求方式
//                    conn.setConnectTimeout(5000);//设置超时时间（毫秒）
//                    conn.setDoOutput(true);//设置为true，可以打开输出流
//                    OutputStream outputStream = conn.getOutputStream();//得到输出流
//                    outputStream.write(param.getBytes(StandardCharsets.UTF_8));//写数据
//                    outputStream.flush();//清空缓冲区
//                    outputStream.close();//关闭输出流
//                    //判断网络访问是否成功
//                    if (conn.getResponseCode() == HTTP_OK) {
//                        //获取输入流
//                        InputStream stream = conn.getInputStream();
//                        Map<String, List<String>> cookies = conn.getHeaderFields();
//                        List<String> setCookies = cookies.get("Set-Cookie");
//                        System.out.println(setCookies.toString());
//                        for (String str:setCookies) {
//                            if(str.startsWith("JSESSIONID")){
//                                String[] split = str.split(";");
//                                sessions= split[0];
//                                break;
//                            }
//                        }
//                        //从流中获取字符串
//                        String json = StreamUtil.stream2String(stream);
//                        Message msg = new Message();
//                        msg.obj = json;
//                        handler.sendMessage(msg);
//                    }
//                    conn.disconnect();//关闭连接
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }.start();

        Map<String, Object> params=new HashMap<>();
        params.put("username",name);
        params.put("password",pwd);
        HttpUrlConnectionUtils.doPost(this, link, new HttpCallbackStringListener() {
            @Override
            public void onFinish(String response) {
                Intent intent=new Intent(LoginActivity.this,CollectActivity.class);
                startActivity(intent);
            }

            @Override
            public void onError(Exception e) {

            }
        },params);
    }
}